import {getRequest} from './request';

export const initMenu = (router, store) => {
    if (store.state.routes.length > 0) {
        return;
    }

    getRequest('/system/config/menu/').then(data => {
        if (data) {
            console.log(data)
            //格式化Router
            let fmtRoutes = formatRoutes(data);
            //添加到router
            router.addRoutes(fmtRoutes);
            //将数组存入vuex
            store.commit('INIT_ROUTES', fmtRoutes);
            //连接WebSocket
            // store.dispatch('connect');
        }
    })
}

export const formatRoutes = (routes) => {
    let fmtRoutes = [];
    routes.forEach(router => {
        let {
            path,
            component,
            name,
            icon,
            children,
        } = router;
        if (children && children instanceof Array) {
            //递归
            children = formatRoutes(children);
        }
        let fmRouter = {
            path: path,
            name: name,
            icon: icon,
            children: children,
            component(resolve) {
                if (component.startsWith('Home')) {
                    require(['../views/' + component + '.vue'], resolve);
                } else if (component.startsWith('Bas')) {
                    require(['../views/bas/' + component + '.vue'], resolve);
                } else if (component.startsWith('Emp')) {
                    require(['../views/emp/' + component + '.vue'], resolve);
                } else if (component.startsWith('Sal')) {
                    require(['../views/sal/' + component + '.vue'], resolve);
                } else if (component.startsWith('Dis')) {
                    require(['../views/dis/' + component + '.vue'], resolve);
                } else if (component.startsWith('Tra')) {
                    require(['../views/tra/' + component + '.vue'], resolve);
                } else if (component.startsWith('Tol')) {
                    require(['../views/tol/' + component + '.vue'], resolve);
                } else if (component.startsWith('Ana')) {
                    require(['../views/ana/' + component + '.vue'], resolve);
                } else if (component.startsWith('Sys')) {
                    require(['../views/sys/' + component + '.vue'], resolve);
                }
            }
        }
        fmtRoutes.push(fmRouter)
    });
    return fmtRoutes;
}